Completed
Push — master ( 3f33f1...179d8a )
by Ruben de
01:12
created

rest_client.js ➔ RestClient   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 4
c 2
b 0
f 1
nc 6
dl 0
loc 31
rs 8.5806
nop 1
1
var _ = require('lodash');
2
var Request = require('./request');
3
var q = require('q');
4
5
/**
6
 * Intermediate class to create HTTP requests
7
 *
8
 *
9
 * @param options       object{
10
 *                          host: '',
11
 *                          endpoint: '', // base url for .request
12
 *                          apiKey: 'API_KEY',
13
 *                          apiSecret: 'API_SECRET'
14
 *                      }
15
 * @constructor
16
 * @constructor
17
 */
18
var RestClient = function(options) {
19
    var self = this;
20
21
    self.apiKey = options.apiKey;
22
    self.apiSecret = options.apiSecret;
23
    self.https = options.https;
24
    self.host = options.host;
25
    self.port = options.port;
26
    self.endpoint = options.endpoint;
27
28
    self.btccom = !!options.btccom;
29
    if (typeof options.throttleRequestsTimeout !== "undefined") {
30
        self.throttleRequestsTimeout = options.throttleRequestsTimeout;
31
    } else if (self.btccom) {
32
        self.throttleRequestsTimeout = 350;
33
    } else {
34
        self.throttleRequestsTimeout = 0;
35
    }
36
    self.throttleRequests = self.throttleRequestsTimeout > 0;
37
    self.nextRequest = null;
38
39
    self.defaultParams = {};
40
41
    if (self.apiKey) {
42
        self.defaultParams['api_key'] = self.apiKey;
43
    }
44
45
    self.defaultHeaders = _.defaults({}, {
46
        'X-SDK-Version': 'blocktrail-sdk-nodejs/' + require('./pkginfo').VERSION
47
    }, options.defaultHeaders);
48
};
49
50
RestClient.prototype.throttle = function() {
51
    var self = this;
52
    var deferred = q.defer();
53
54
    if (this.throttleRequests) {
55
        if (this.nextRequest) {
56
            // chain onto the previous delay
57
            this.nextRequest = this.nextRequest.then(function() {
58
                deferred.resolve();
59
60
                return q.delay(self.throttleRequestsTimeout);
61
            });
62
        } else {
63
            // first time we just resolve and setup the delay for the next request
64
            this.nextRequest = q.delay(self.throttleRequestsTimeout);
65
            deferred.resolve();
66
        }
67
    } else {
68
        deferred.resolve();
69
    }
70
71
    return deferred.promise;
72
};
73
74
RestClient.prototype.create_request = function(options) {
75
    var self = this;
76
77
    options = _.defaults({}, options, {
78
        https: self.https,
79
        host: self.host,
80
        port: self.port,
81
        endpoint: self.endpoint,
82
        apiKey: self.apiKey,
83
        apiSecret: self.apiSecret,
84
        params: _.defaults({}, self.defaultParams),
85
        headers: _.defaults({}, self.defaultHeaders)
86
    });
87
88
    return new Request(options);
89
};
90
91
RestClient.prototype.post = function(path, params, data, fn, requireAuth) {
92
    var self = this;
93
94
    requireAuth = typeof requireAuth === "undefined" ? true : requireAuth;
95
96
    var options = {};
97
    if (requireAuth) {
98
        options['auth'] = 'http-signature';
99
    }
100
101
    return self.throttle().then(function() {
102
        return self.create_request(options).request('POST', path, params, data, fn);
103
    });
104
};
105
106
RestClient.prototype.put = function(path, params, data, fn, requireAuth) {
107
    var self = this;
108
109
    requireAuth = typeof requireAuth === "undefined" ? true : requireAuth;
110
111
    var options = {};
112
    if (requireAuth) {
113
        options['auth'] = 'http-signature';
114
    }
115
116
    return self.throttle().then(function() {
117
        return self.create_request(options).request('PUT', path, params, data, fn);
118
    });
119
};
120
121
RestClient.prototype.get = function(path, params, doHttpSignature, fn) {
122
    var self = this;
123
124
    if (typeof doHttpSignature === "function") {
125
        fn = doHttpSignature;
126
        doHttpSignature = false;
127
    }
128
129
    var options = {};
130
131
    if (doHttpSignature) {
132
        options['auth'] = 'http-signature';
133
    }
134
135
    if (self.btccom && typeof fn !== "undefined") {
136
        throw new Error("we should be using callbackify!");
137
    }
138
139
    return self.throttle().then(function() {
140
        return self.create_request(options).request('GET', path, params, null, fn);
141
    });
142
};
143
144
RestClient.prototype.delete = function(path, params, data, fn, requireAuth) {
145
    var self = this;
146
147
    requireAuth = typeof requireAuth === "undefined" ? true : requireAuth;
148
149
    var options = {};
150
    if (requireAuth) {
151
        options['auth'] = 'http-signature';
152
    }
153
154
    return self.throttle().then(function() {
155
        return self.create_request(options).request('DELETE', path, params, data, fn);
156
    });
157
};
158
159
module.exports = function(options) {
160
    return new RestClient(options);
161
};
162